<template>
	<view class="message-center-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left">
				<uni-icons type="left" size="20" @click="goBack"></uni-icons>
			</view>
			<view class="navbar-title">消息中心</view>
			<view class="navbar-right">
				<uni-icons type="trash" size="20" @click="clearAllMessages"></uni-icons>
			</view>
		</view>
		
		<!-- 消息分类标签 -->
		<view class="message-tabs">
			<view 
				class="tab-item" 
				:class="{ active: currentTab === tab.key }"
				v-for="tab in messageTabs" 
				:key="tab.key"
				@click="switchTab(tab.key)"
			>
				<view class="tab-content">
					<text class="tab-text">{{ tab.name }}</text>
					<view v-if="tab.unreadCount > 0" class="unread-badge">{{ tab.unreadCount }}</view>
				</view>
			</view>
		</view>
		
		<!-- 消息列表 -->
		<view class="message-list">
			<view v-if="currentMessages.length === 0" class="empty-message">
				<uni-icons type="chatbubble" size="48" color="#ccc"></uni-icons>
				<text class="empty-text">暂无{{ getCurrentTabName() }}消息</text>
			</view>
			
			<view 
				v-else
				class="message-item" 
				:class="{ 
					unread: !message.isRead,
					read: message.isRead 
				}"
				v-for="(message, index) in currentMessages" 
				:key="index"
				@click="readMessage(message)"
			>
				<view class="message-icon">
					<uni-icons :type="getMessageIcon(message.type)" size="20" :color="getMessageIconColor(message.type)"></uni-icons>
				</view>
				<view class="message-content">
					<view class="message-header">
						<text class="message-title" :class="{ 'unread-title': !message.isRead }">{{ message.title }}</text>
						<text class="message-time">{{ formatMessageTime(message.createTime) }}</text>
					</view>
					<view class="message-preview" :class="{ 'unread-preview': !message.isRead }">{{ message.content }}</view>
				</view>
				<view v-if="!message.isRead" class="unread-dot"></view>
			</view>
		</view>
		
		<!-- 加载更多 -->
		<view v-if="hasMore" class="load-more" @click="loadMoreMessages">
			<text class="load-more-text">加载更多</text>
		</view>
	</view>
</template>

<script>
	import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
	import { messageApi } from '@/api/index.js';
	
	export default {
		components: { 
			uniIcons
		},
		data() {
			return {
				userId: 1, // 默认用户ID，实际应该从登录状态获取
				currentTab: 'all',
				messageTabs: [
					{ key: 'all', name: '全部', count: 0 },
					{ key: 'system', name: '系统', count: 0 },
					{ key: 'activity', name: '活动', count: 0 },
					{ key: 'order', name: '订单', count: 0 }
				],
				allMessages: [],
				hasMore: false
			};
		},
		computed: {
			currentMessages() {
				if (this.currentTab === 'all') {
					return this.allMessages;
				}
				return this.allMessages.filter(message => message.type === this.currentTab);
			}
		},
		async onLoad() {
			// 页面加载时获取消息数据
			await this.loadMessages();
		},
		onShow() {
			// 页面显示时刷新数据
			this.loadMessages();
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 加载消息数据
			async loadMessages() {
				try {
					console.log('开始获取消息数据...');
					
					// 使用新的API接口获取所有消息
					const result = await messageApi.getAllMessages();
					
					console.log('消息API返回结果:', result);
					console.log('result.code:', result.code);
					console.log('result.data:', result.data);
					console.log('result.msg:', result.msg);
					
					// 检查API响应
					if (result && result.code === 200 && result.data && result.data.length > 0) {
						// 处理消息数据
						this.allMessages = this.processMessageData(result.data);
						await this.updateMessageStats();
						console.log('成功从后端获取消息数据，数量:', this.allMessages.length);
					} else {
						console.log('后端数据获取失败，响应详情:', {
							hasResult: !!result,
							code: result?.code,
							hasData: !!result?.data,
							dataLength: result?.data?.length
						});
						this.allMessages = [];
					}
				} catch (error) {
					console.error('加载消息数据失败:', error);
					this.allMessages = [];
				}
			},
			
			// 处理消息数据，添加isRead属性
			processMessageData(messages) {
				return messages.map(msg => ({
					...msg,
					isRead: msg.status === 'read' // 假设status为'read'表示已读
				}));
			},

			// 更新标签页数量
			async updateMessageStats() {
				try {
					// 计算各类型消息数量
					const allCount = this.allMessages.length;
					const systemCount = this.allMessages.filter(msg => msg.type === 'system').length;
					const activityCount = this.allMessages.filter(msg => msg.type === 'activity').length;
					const orderCount = this.allMessages.filter(msg => msg.type === 'order').length;
					const unreadCount = this.allMessages.filter(msg => !msg.isRead).length;
					
					// 更新标签页数量
					this.messageTabs[0].count = allCount;
					this.messageTabs[1].count = systemCount;
					this.messageTabs[2].count = activityCount;
					this.messageTabs[3].count = orderCount;
					
					console.log('成功更新消息统计，各类型数量:', {
						all: allCount,
						system: systemCount,
						activity: activityCount,
						order: orderCount,
						unread: unreadCount
					});
				} catch (error) {
					console.error('更新消息统计失败:', error);
				}
			},
			
			// 切换标签
			switchTab(tabKey) {
				this.currentTab = tabKey;
			},
			
			// 获取当前标签名称
			getCurrentTabName() {
				const tab = this.messageTabs.find(t => t.key === this.currentTab);
				return tab ? tab.name : '';
			},
			
			// 阅读消息
			async readMessage(message) {
				console.log('=== 开始阅读消息 ===');
				console.log('消息对象:', message);
				console.log('当前未读状态:', message.isRead);
				
				if (!message.isRead) {
					try {
						console.log('调用API标记为已读，消息ID:', message.id);
						
						// 调用API标记为已读
						const result = await messageApi.markMessageAsRead(message.id);
						
						console.log('API调用结果:', result);
						
						if (result && result.code === 200) {
							console.log('API调用成功，开始更新本地状态');
							
							// 更新本地消息状态
							message.isRead = true;
							message.status = 'read';
							
							console.log(`消息 ${message.id} 已标记为已读`);
							console.log('更新后的消息对象:', message);
							
							// 立即更新本地统计，减少未读数量
							this.updateLocalUnreadCount(message.type);
							
							// 重新获取消息统计并更新标签页
							await this.updateMessageStats();
						} else {
							console.error('API调用失败:', result.msg);
						}
					} catch (error) {
						console.error('标记已读失败:', error);
					}
				} else {
					console.log('消息已经是已读状态，无需标记');
				}
				
				console.log('=== 阅读消息结束 ===');
				
				// 显示消息详情
				uni.showModal({
					title: message.title,
					content: message.content,
					showCancel: false,
					confirmText: '知道了'
				});
			},
			
			// 清空所有消息
			async clearAllMessages() {
				uni.showModal({
					title: '确认清空',
					content: '确定要清空所有消息吗？此操作不可恢复。',
					success: async (res) => {
						if (res.confirm) {
							this.allMessages = [];
							this.messageTabs.forEach(tab => {
								tab.count = 0;
								tab.unreadCount = 0; // 清空未读数量
							});
							uni.showToast({
								title: '已清空所有消息',
								icon: 'success'
							});
						}
					}
				});
			},
			
			// 加载更多消息
			async loadMoreMessages() {
				// 这里可以实现分页加载逻辑
				uni.showToast({
					title: '没有更多消息了',
					icon: 'none'
				});
				this.hasMore = false;
			},

			// 格式化消息时间
			formatMessageTime(timestamp) {
				const date = new Date(timestamp);
				const now = new Date();
				const diffMinutes = (now - date) / (1000 * 60);

				if (diffMinutes < 60) {
					return `${Math.floor(diffMinutes)}分钟前`;
				} else if (diffMinutes < 24 * 60) {
					return `${Math.floor(diffMinutes / 60)}小时前`;
				} else {
					return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
				}
			},

			// 获取消息图标
			getMessageIcon(type) {
				switch (type) {
					case 'system':
						return 'chatbubble';
					case 'activity':
						return 'gift';
					case 'order':
						return 'cart';
					default:
						return 'chatbubble';
				}
			},

			// 获取消息图标颜色
			getMessageIconColor(type) {
				switch (type) {
					case 'system':
						return '#007AFF'; // 系统消息通常是蓝色
					case 'activity':
						return '#FFC107'; // 活动消息通常是黄色
					case 'order':
						return '#4CAF50'; // 订单消息通常是绿色
					default:
						return '#666'; // 默认颜色
				}
			},

			// 更新本地未读数量
			updateLocalUnreadCount(type) {
				// 更新对应类型的标签页
				const typeTab = this.messageTabs.find(t => t.key === type);
				if (typeTab) {
					typeTab.unreadCount--;
					if (typeTab.unreadCount < 0) {
						typeTab.unreadCount = 0;
					}
					console.log(`本地未读数量更新: ${typeTab.name} 剩余未读 ${typeTab.unreadCount}`);
				}
				
				// 更新"全部"标签页
				const allTab = this.messageTabs.find(t => t.key === 'all');
				if (allTab) {
					allTab.unreadCount--;
					if (allTab.unreadCount < 0) {
						allTab.unreadCount = 0;
					}
					console.log(`本地未读数量更新: 全部 剩余未读 ${allTab.unreadCount}`);
				}
			},

			// 显示调试信息
			showDebugInfo() {
				console.log('=== 调试信息 ===');
				console.log('当前用户ID:', this.userId);
				console.log('当前标签:', this.currentTab);
				console.log('消息总数:', this.allMessages.length);
				console.log('当前显示消息:', this.currentMessages.length);
				console.log('标签页配置:', this.messageTabs);
				console.log('=== 调试信息结束 ===');
			}
		}
	};
</script>

<style scoped>
	.message-center-container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}
	
	.custom-navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
	}
	
	.navbar-left, .navbar-right {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.navbar-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.message-tabs {
		display: flex;
		background-color: #fff;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
	}
	
	.tab-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
	}
	
	.tab-content {
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.tab-text {
		font-size: 28rpx;
		color: #666;
		margin-right: 8rpx;
	}
	
	.tab-item.active .tab-text {
		color: #007AFF;
		font-weight: bold;
	}

	.unread-badge {
		background-color: #ff4757;
		color: #fff;
		font-size: 18rpx;
		padding: 2rpx 6rpx;
		border-radius: 12rpx;
		min-width: 24rpx;
		height: 24rpx;
		text-align: center;
		line-height: 20rpx;
		font-weight: bold;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 8rpx;
		box-shadow: 0 2rpx 4rpx rgba(255, 71, 87, 0.3);
	}
	
	.message-list {
		padding: 20rpx;
	}
	
	.empty-message {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		color: #999;
	}
	
	.empty-text {
		margin-top: 20rpx;
		font-size: 28rpx;
	}
	
	.message-item {
		display: flex;
		align-items: flex-start;
		padding: 30rpx;
		background-color: #fff;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		position: relative;
		transition: all 0.3s ease;
	}
	
	.message-item.unread {
		border-left: 6rpx solid #007AFF;
		background-color: #f8f9ff; /* 未读消息背景色 */
		box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.1);
	}
	
	.message-item.read {
		background-color: #f9f9f9; /* 已读消息背景色 */
		border-left: 6rpx solid #e0e0e0;
		opacity: 0.8;
	}

	.message-icon {
		margin-right: 20rpx;
		margin-top: 4rpx;
	}
	
	.message-content {
		flex: 1;
	}
	
	.message-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10rpx;
	}
	
	.message-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.message-title.unread-title {
		font-weight: bold;
	}
	
	.message-time {
		font-size: 24rpx;
		color: #999;
	}
	
	.message-preview {
		font-size: 28rpx;
		color: #666;
		line-height: 1.5;
	}

	.message-preview.unread-preview {
		font-weight: bold;
	}
	
	.unread-dot {
		position: absolute;
		top: 30rpx;
		right: 30rpx;
		width: 16rpx;
		height: 16rpx;
		background-color: #007AFF;
		border-radius: 50%;
	}
	
	.load-more {
		text-align: center;
		padding: 30rpx;
		color: #999;
	}
	
	.load-more-text {
		font-size: 28rpx;
	}
	
	.test-section {
		padding: 30rpx;
	}
	
	.test-button {
		background-color: #007AFF;
		color: #fff;
		padding: 20rpx 40rpx;
		border-radius: 10rpx;
		text-align: center;
	}
	
	.test-button-text {
		font-size: 28rpx;
	}
</style>
